<template>
  <HPopup
      v-model:show="innerShow"
      :title="manualConfig?.manual.manualSelectorButtonName"
      class="relation-form-list">
    <VerticalLayout bodyELementId="manual-relation-form-list-body">
      <template #header>
        <ManualRelationSearch
            ref="searchRef"
            :context="context"
            @search="() => search(true)"
            :formDefinition="formDefinition"
            :manualConfig="manualConfig"/>
      </template>

      <ManualRelationList
          :subForm="subForm"
          :selectionType="selectionType"
          :dataSource="dataSource"
          :manualConfig="manualConfig"
          :context="context"
          :formDefinition="formDefinition"
          v-model:selectedRows="selectedRows"/>

      <template #footer>
        <RelationFormListFooter
            :selectionType="selectionType"
            @selectedOk="selectedOk"
            :formDefinition="formDefinition"
            :manualConfig="manualConfig"
            v-model:selectedRows="selectedRows"
            :select-all="selectAll"
            @toggleSelectAll="toggleSelectAll"/>
      </template>
    </VerticalLayout>
  </HPopup>
</template>
<script setup>
import HPopup from '@comp/HPopup/HPopup.vue';
import {computed, nextTick, ref, shallowRef, watch} from 'vue';
import {closePopup, createProps, readFormDefinitionVo} from '@/utils';
import {getAction, postAction} from '@/request';
import VerticalLayout from '@comp/Layout/VerticalLayout.vue';
import ManualRelationSearch from '@comp/FormEngine/field/relation/RelationFormList/ManualRelationSearch.vue';
import ManualRelationList from '@comp/FormEngine/field/relation/RelationFormList/ManualRelationList.vue';
import RelationFormListFooter from '@comp/FormEngine/field/relation/RelationFormList/RelationFormListFooter.vue';
import {showToast} from 'vant';

defineOptions({name: 'RelationFormList'});
const emits = defineEmits(['update:show']);
const loading = shallowRef(false);
const props = defineProps({
  show: createProps(Boolean),
  subFormId: createProps(String),
  rowId: createProps(String),
  rowIndex: createProps(String),
  sourceFormId: createProps(String),
  context: createProps(Object, () => undefined),
  manualConfig: createProps(Object, () => undefined),
});
const searchRef = shallowRef();
const formDefinition = shallowRef();
const dataSource = shallowRef();
const selectedRows = ref();
const selectionType = computed(() => {
  return 'radio'
})
const innerShow = computed({
  get() {
    return props.show;
  },
  set(value) {
    emits('update:show', value);
  }
});
const pagination = ref({
  pageNo: 1,
  pageSize: 10,
})

const manualId = computed(() => {
  return props?.manualConfig?.manual?.id;
});
const formModel = computed(() => {
  return props.context?.formModel || {};
});
const relationId = computed(() => {
  return props?.manualConfig?.relation?.id;
});
const formId = computed(() => {
  return props?.manualConfig?.relation?.relationTargetFormId;
});
const subForm = computed(() => {
  return props.context.formDefinition.subForms.find(item => item.id === props.subFormId);
});
const selectAll = computed(() => {
  if (!dataSource.value || !dataSource.value.length) return false;
  let idColumnName = `${formDefinition.value?.id}&formId`;

  for (let i = 0; i < dataSource.value.length; i++) {
    let temp = dataSource.value[i];
    let index = (selectedRows.value || []).findIndex(item => item[idColumnName] === temp[idColumnName]);
    if (index === -1) {
      return false;
    }
  }
  return true;
});

function selectedOk() {
  if (!selectedRows.value || !selectedRows.value.length) {
    return showToast('请选择关联单据');
  }
  // closePopup();
  let data = {
    actionId: props.context.actionId,
    formModel: props.context.formModel,
    manualId: props.manualConfig.manual.id,
    relationData: selectedRows.value[0],
    relationId: props.manualConfig.relation.id,
    rowId: props.rowId,
    sourceFormDefinitionId: props.manualConfig.relation.relationSourceFormId,
    targetFormDefinitionId: props.manualConfig.relation.relationTargetFormId
  };

  loading.value = true;
  postAction('/form/manualRelationById', data).then(data => {
    loading.value = false;
    if (data.success) {
      let {formModel} = data.result;
      props.context.changeFormModel(formModel)
      closePopup();
    }
  })
}

function toggleSelectAll() {
  if (!dataSource.value || !dataSource.value.length) return false;
  let idColumnName = `${formDefinition.value?.id}&formId`;


  if (selectAll.value) {
    //当前已经是全选了, 需要删除
    for (let i = 0; i < dataSource.value.length; i++) {
      let temp = dataSource.value[i];
      let index = (selectedRows.value || []).findIndex(item => item[idColumnName] === temp[idColumnName]);
      if (index !== -1) {
        selectedRows.value.splice(index, 1);
      }
    }
  } else {
    //当前不是全选, 需要添加
    for (let i = 0; i < dataSource.value.length; i++) {
      let temp = dataSource.value[i];
      let index = (selectedRows.value || []).findIndex(item => item[idColumnName] === temp[idColumnName]);
      if (index === -1) {
        selectedRows.value.push(temp);
      }
    }
  }
}

function getQueryParams(resetDataSource) {
  if (resetDataSource) {
    pagination.value.pageNo = 1;
    dataSource.value = [];
  } else {
    pagination.value.pageNo++;
  }
  return {
    formId: formId.value,
    formModel: formModel.value,
    manualId: manualId.value,
    pageNo: pagination.value.pageNo,
    pageSize: pagination.value.pageSize,
    relationId: relationId.value,
    rowId: props.rowId,
    rowIndex: props.rowIndex,
    sourceFormId: props.context.formDefinition.id,
    userConditions: searchRef.value.getParams(),
  };
}

function search(resetDataSource) {
  let data = getQueryParams(resetDataSource);
  loading.value = true;
  postAction('/form/queryManualRelationData', data).then(data => {
    loading.value = false;
    if (data.success) {
      dataSource.value = data.result.records;
    }
  });
}

function loadFormDefinition() {
  let id = props.manualConfig?.relation?.relationTargetFormId;
  if (!id) return;
  loading.value = true;
  getAction("/form/queryById", {id}).then(data => {
    loading.value = false;
    if (data.success) {
      formDefinition.value = readFormDefinitionVo(data.result);
    }
  });
}

watch(() => props.show, () => {
  nextTick(() => {
    if (props.show) {
      search(true);
      loadFormDefinition();
      selectedRows.value = []
    }
  });
}, {
  immediate: true,
});
</script>
<style lang="less">
.relation-form-list {
  min-height: 100vh !important;
  height: 100vh !important;
  border-radius: 0 !important;
}
</style>